import { loginByPhoneAndPwd, loginByPhone, loginByKey, logout, getUserInfo, getTopTitle, getSysconfig } from './api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import variables from '@/styles/element-variables.scss'

import CryptoJS from '@/utils/aes.js'
CryptoJS.$getAES = (encrypted) => {
  var key = CryptoJS.enc.Hex.parse('e2f29cb8df39a368e2f29cb8df39a368')
  var iv = CryptoJS.enc.Hex.parse('5e92442523d44e7c167fcc6f98d40157')
  var string = encrypted
  var data = CryptoJS.AES.decrypt(string, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  var uncrypted = data.toString(CryptoJS.enc.Utf8)
  return uncrypted
}

const store = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    theme: variables.theme,
    browserHeaderTitle: '',
    checkurl: []
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_THEME: (state, theme) => {
      state.theme = theme
    },
    SET_BROWSERHEADERTITLE: (state, action) => {
      state.browserHeaderTitle = action.browserHeaderTitle
    },
    SET_CHECKURL: (state, checkurl) => {
      state.checkurl = checkurl
    }
  },

  actions: {
    themeChange({ commit }, theme) {
      commit('SET_THEME', theme)
    },
    // 获取token
    ToObtaintoken({ commit }) {
      return new Promise((resolve, reject) => {
        toObtaintoken().then(response => {
          const data = response.data
          commit('SET_TOKEN', data.data)
          setToken(data.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 平台端通过key自动登录
    LoginByKey({ commit }, UUID) {
      return new Promise((resolve, reject) => {
        loginByKey(UUID).then(response => {
          const data = response.data
          const NEWAES = CryptoJS.$getAES(data.data.NEWKEY)
          localStorage.setItem('NEWAES', NEWAES)
          commit('SET_TOKEN', data.data.ttsxyhcs)
          commit('SET_ROLES', [])
          setToken(data.data.ttsxyhcs)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 手机号+密码登录 -----新
    LoginByPhoneAndPwd({ commit }, userInfo) {
      const phoneNumber = userInfo.phoneNumber
      const password = userInfo.password
      return new Promise((resolve, reject) => {
        loginByPhoneAndPwd(phoneNumber, password).then(response => {
          const data = response.data
          const NEWAES = CryptoJS.$getAES(data.data.NEWKEY)
          localStorage.setItem('NEWAES', NEWAES)
          commit('SET_TOKEN', data.data.ttsxyhcs)
          setToken(data.data.ttsxyhcs)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 短信验证码登录
    LoginByPhone({ commit }, userInfo) {
      const phoneNumber = userInfo.phoneNumber
      const smsCode = userInfo.smsCode
      return new Promise((resolve, reject) => {
        loginByPhone(phoneNumber, smsCode).then(response => {
          const data = response.data
          const NEWAES = CryptoJS.$getAES(data.data.NEWKEY)
          localStorage.setItem('NEWAES', NEWAES)
          commit('SET_TOKEN', data.data.ttsxyhcs)
          setToken(data.data.ttsxyhcs)
          resolve()
        }).catch(error => {
          console.log('error', error)
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        localStorage.setItem('current', JSON.stringify({ token: getToken() }))
        getUserInfo(state.token).then(response => {
          if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
            reject('')
          }
          const data = response.data.data
          // console.log(data)
          commit('SET_USER', data)
          commit('SET_ROLES', ['admin'].concat(data.menuDatas))
          commit('SET_NAME', data.userRealname)
          commit('SET_AVATAR', data.headPortrait)
          let checkurl = []
          try {
            checkurl = JSON.parse(data.rcInfos)
          } catch (error) { }
          commit('SET_CHECKURL', checkurl)
          resolve(response)
        }).catch(error => {
          reject('')
        })
      })
    },
    GetUserRoles({ commit, state }) {
      commit('SET_ROLES', ['admin'])
    },
    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        localStorage.setItem('isLogin', 0)
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRole({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.role)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          resolve()
        })
      })
    },

    /**
     * 更改title
     */
    ChangeHeaderTitle({ commit }, title) {
      commit('SET_BROWSERHEADERTITLE', {
        browserHeaderTitle: title
      })
    },

    /**
     * 获取Title
     */
    GetTitle({ commit, state }) {
      return new Promise((resolve, reject) => {
        getTopTitle({ name: 'PAGE_TOP_TITLE' }).then((response) => {
          if (response) {
            commit('SET_BROWSERHEADERTITLE', {
              browserHeaderTitle: response.data.data.configValue
            })
          } else {
            commit('SET_BROWSERHEADERTITLE', {
              browserHeaderTitle: '数字化工会管理系统'
            })
          }
          resolve()
        }).catch(error => {
          reject('')
        })
      })
    },
    /**
     * 获取是否上传文件到oss的配置
     */
    GetSysConfig({ commit, state }) {
      return new Promise((resolve, reject) => {
        getSysconfig({ name: 'FILE_SAVE_THIRD_CONFIG' }).then((response) => {
          sessionStorage.setItem('FILE_SAVE_THIRD_CONFIG', response.data.data.configValue)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default store
